﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.StaticFiles;
using System.Net;

namespace CommonUtils
{
    public static class CoreHttpUtil
    {
        private static StringCountMap _ipCountMap = new StringCountMap();

        static CoreHttpUtil()
        {
            ThreadUtil.LoopDelay(_ipCountMap.Clear, 3600);
        }

        public static bool CheckAttack(HttpRequest request)
        {
            var key = request.Host.Value;
            _ipCountMap.Sum(key);
            return _ipCountMap.Get(key) > 1000;
        }

        //StaticFileResponseContext

        public static bool CheckAttack(StaticFileResponseContext context)
        => CheckAttack(context.Context.Request);

        public static void Forbid(StaticFileResponseContext context)
        {
            var response = context.Context.Response;
            response.StatusCode = HttpUtil.GetStatusCode(HttpStatusCode.Forbidden);
            response.ContentLength = 0;
            response.Body = BinaryUtil.EmptyStream;
        }

        public static void ForbidAttack(StaticFileResponseContext context)
        {
            if (CheckAttack(context.Context.Request))
                Forbid(context);
        }

        //ResourceExecutedContext

        public static bool CheckAttack(ResourceExecutedContext context)
         => CheckAttack(context.HttpContext.Request);

        public static void Forbid(ResourceExecutedContext context)
        => context.Result = StaticActionResult.Forbid;

        public static void ForbidAttack(ResourceExecutedContext context)
        {
            if (CheckAttack(context.HttpContext.Request))
                Forbid(context);
        }
    }
}
